"""
督导系统模型使用示例
演示如何使用训练好的模型进行预测
"""

import sys
import os
import logging
import numpy as np
import pandas as pd

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from models.risk_prediction_model import RiskPredictionModel
from models.problem_classification_model import ProblemClassificationModel
from models.heatmap_prediction_model import HeatmapPredictionModel
from config.model_config import config

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def example_risk_prediction():
    """风险预警模型使用示例"""
    
    logger.info("=== 风险预警模型使用示例 ===")
    
    try:
        # 加载模型
        model = RiskPredictionModel()
        model.load_model()
        
        # 创建示例特征数据
        sample_features = pd.DataFrame({
            'area_code': ['A001', 'A002', 'A003'],
            'problem_count': [15, 8, 25],
            'severity_score': [12, 5, 30],
            'problem_type_count': [3, 2, 5],
            'avg_rectification_rate': [0.7, 0.9, 0.4],
            'population': [10000, 8000, 15000],
            'area_size': [5.2, 3.1, 8.7]
        })
        
        # 预测高风险区域
        risk_areas = model.predict_risk_areas(sample_features, top_k=5)
        
        logger.info("高风险区域预测结果：")
        for area in risk_areas:
            logger.info(f"区域: {area['area_code']}, "
                       f"风险概率: {area['risk_probability']:.4f}, "
                       f"风险等级: {area['risk_level']}")
        
        # 预测整改难度
        difficulty = model.predict_rectification_difficulty(sample_features)
        
        logger.info("\n整改难度预测结果：")
        for diff in difficulty[:3]:
            logger.info(f"区域: {diff['area_code']}, "
                       f"难度得分: {diff['difficulty_score']:.4f}, "
                       f"成功率: {diff['predicted_success_rate']:.4f}")
        
    except Exception as e:
        logger.error(f"风险预警模型示例失败: {e}")

def example_problem_classification():
    """问题分类模型使用示例"""
    
    logger.info("\n=== 问题分类模型使用示例 ===")
    
    try:
        # 加载模型
        model = ProblemClassificationModel()
        model.load_model()
        
        # 示例文本
        sample_texts = [
            "发现施工现场存在安全隐患，工人未佩戴安全帽，需要立即整改",
            "垃圾堆放不当，造成环境污染，影响周边居民生活",
            "建筑质量不符合标准，发现多处裂缝，问题较为严重",
            "管理制度执行不到位，相关人员培训不足"
        ]
        
        # 进行分类预测
        results = model.predict(sample_texts)
        
        logger.info("问题分类结果：")
        for i, result in enumerate(results):
            logger.info(f"\n文本 {i+1}: {result['text'][:30]}...")
            logger.info(f"问题类型: {result['predicted_problem_type']} "
                       f"(置信度: {result['problem_type_confidence']:.4f})")
            logger.info(f"严重程度: {result['predicted_severity']} "
                       f"(置信度: {result['severity_confidence']:.4f})")
        
    except Exception as e:
        logger.error(f"问题分类模型示例失败: {e}")

def example_heatmap_prediction():
    """热力图预测模型使用示例"""
    
    logger.info("\n=== 热力图预测模型使用示例 ===")
    
    try:
        # 加载模型
        model = HeatmapPredictionModel()
        model.load_model()
        
        # 创建示例历史数据 (时间序列的空间网格数据)
        # 形状: (时间步数, 网格高度, 网格宽度)
        time_steps = 7  # 7天历史数据
        height, width = 20, 20  # 20x20网格
        
        # 生成模拟的历史热力图数据
        np.random.seed(42)
        historical_data = np.random.poisson(2, (time_steps, height, width)).astype(np.float32)
        
        # 添加一些热点区域
        for t in range(time_steps):
            # 热点1
            historical_data[t, 8:12, 8:12] += np.random.poisson(5, (4, 4))
            # 热点2  
            historical_data[t, 15:18, 5:8] += np.random.poisson(3, (3, 3))
        
        logger.info(f"历史数据形状: {historical_data.shape}")
        logger.info(f"历史数据统计: 均值={historical_data.mean():.2f}, "
                   f"最大值={historical_data.max()}, 最小值={historical_data.min()}")
        
        # 预测未来热力图
        prediction_steps = 3  # 预测未来3天
        predicted_heatmaps = model.predict_heatmap(historical_data, prediction_steps)
        
        logger.info(f"\n预测结果形状: {predicted_heatmaps.shape}")
        
        # 分析每个预测步骤
        for step in range(prediction_steps):
            heatmap = predicted_heatmaps[step, 0]  # 去除batch维度
            logger.info(f"\n第 {step+1} 天预测:")
            logger.info(f"  预测热力图统计: 均值={heatmap.mean():.2f}, "
                       f"最大值={heatmap.max():.2f}, 最小值={heatmap.min():.2f}")
            
            # 识别风险热点
            hotspots = model.predict_risk_hotspots(heatmap, threshold_percentile=85)
            logger.info(f"  识别到 {len(hotspots)} 个风险热点区域")
            
            for i, hotspot in enumerate(hotspots[:3]):  # 显示前3个
                logger.info(f"    热点 {i+1}: 位置({hotspot['grid_x']}, {hotspot['grid_y']}), "
                           f"风险得分={hotspot['risk_score']:.2f}, "
                           f"风险等级={hotspot['risk_level']}")
        
        # 生成地图可视化（如果需要）
        if len(predicted_heatmaps) > 0:
            center_coords = (39.9042, 116.4074)  # 北京坐标
            map_viz = model.generate_heatmap_visualization(
                predicted_heatmaps[0, 0], center_coords
            )
            
            # 保存地图
            map_path = "predicted_heatmap.html"
            map_viz.save(map_path)
            logger.info(f"\n热力图可视化已保存到: {map_path}")
        
    except Exception as e:
        logger.error(f"热力图预测模型示例失败: {e}")

def example_integrated_workflow():
    """集成工作流示例"""
    
    logger.info("\n=== 集成工作流示例 ===")
    logger.info("模拟完整的督导预测工作流程")
    
    try:
        # 步骤1: 问题分类
        logger.info("\n步骤1: 自动分类新发现的问题")
        new_problem = "施工现场发现严重安全隐患，可能导致重大事故"
        
        classification_model = ProblemClassificationModel()
        classification_model.load_model()
        
        classification_result = classification_model.predict([new_problem])[0]
        logger.info(f"问题类型: {classification_result['predicted_problem_type']}")
        logger.info(f"严重程度: {classification_result['predicted_severity']}")
        
        # 步骤2: 风险区域预测
        logger.info("\n步骤2: 识别高风险区域")
        
        risk_model = RiskPredictionModel()
        risk_model.load_model()
        
        sample_areas = pd.DataFrame({
            'area_code': ['A001', 'A002', 'A003', 'A004', 'A005'],
            'problem_count': [20, 5, 35, 12, 8],
            'severity_score': [25, 8, 45, 15, 10],
            'problem_type_count': [4, 2, 6, 3, 2],
            'avg_rectification_rate': [0.6, 0.9, 0.3, 0.7, 0.8]
        })
        
        high_risk_areas = risk_model.predict_risk_areas(sample_areas, top_k=3)
        logger.info("建议优先督导的区域:")
        for area in high_risk_areas:
            logger.info(f"  {area['area_code']}: 风险等级 {area['risk_level']} "
                       f"(概率: {area['risk_probability']:.3f})")
        
        # 步骤3: 热力图预测辅助路线规划
        logger.info("\n步骤3: 预测问题分布热力图，优化督导路线")
        
        heatmap_model = HeatmapPredictionModel()
        heatmap_model.load_model()
        
        # 模拟历史数据
        historical_data = np.random.poisson(1.5, (7, 15, 15)).astype(np.float32)
        predicted_heatmap = heatmap_model.predict_heatmap(historical_data, 1)
        
        hotspots = heatmap_model.predict_risk_hotspots(
            predicted_heatmap[0, 0], threshold_percentile=80
        )
        
        logger.info(f"预测到 {len(hotspots)} 个潜在问题热点")
        logger.info("建议督导路线应重点关注以下区域:")
        for i, hotspot in enumerate(hotspots[:5]):
            logger.info(f"  热点 {i+1}: 网格位置({hotspot['grid_x']}, {hotspot['grid_y']}), "
                       f"风险等级: {hotspot['risk_level']}")
        
        # 步骤4: 综合建议
        logger.info("\n步骤4: 综合AI分析建议")
        logger.info("=" * 50)
        logger.info("📋 督导建议报告:")
        logger.info(f"🚨 新问题分类: {classification_result['predicted_problem_type']} "
                   f"({classification_result['predicted_severity']})")
        logger.info(f"🎯 优先督导区域: {high_risk_areas[0]['area_code']} "
                   f"(风险等级: {high_risk_areas[0]['risk_level']})")
        logger.info(f"🗺️  热点区域数量: {len(hotspots)}")
        logger.info("💡 建议行动: 立即安排督导人员前往高风险区域，重点检查安全隐患")
        
    except Exception as e:
        logger.error(f"集成工作流示例失败: {e}")

def main():
    """主函数"""
    
    logger.info("🚀 督导系统模型使用示例")
    logger.info("=" * 60)
    
    # 检查模型文件是否存在
    model_files = [
        f"{config.data.model_dir}/risk_prediction_model.pkl",
        f"{config.data.model_dir}/problem_classification_model",
        f"{config.data.model_dir}/heatmap_prediction_model.pth"
    ]
    
    missing_models = []
    for model_file in model_files:
        if not os.path.exists(model_file):
            missing_models.append(model_file)
    
    if missing_models:
        logger.warning("⚠️  以下模型文件不存在，请先运行训练:")
        for model in missing_models:
            logger.warning(f"   {model}")
        logger.info("\n运行以下命令进行训练:")
        logger.info("   python train_models.py --use-sample-data --models all")
        return
    
    # 运行示例
    try:
        example_risk_prediction()
        example_problem_classification()
        example_heatmap_prediction()
        example_integrated_workflow()
        
        logger.info("\n" + "=" * 60)
        logger.info("✅ 所有示例运行完成！")
        logger.info("📖 更多详细信息请查看README.md")
        
    except Exception as e:
        logger.error(f"示例运行失败: {e}")

if __name__ == "__main__":
    main() 